package uts.sdk.modules.kuxApiuseOssUploadHelper

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.net.HttpURLConnection
import java.net.URL
import android.content.Context
import android.net.ConnectivityManager

object NetworkUtils {
	
	interface NetworkStateListener {
		fun onNetworkStateAvailable(isAvailable: Boolean)
	}

    /**
     * 检查设备是否连接到网络
     *
     * @return 如果已连接到网络，返回 true；否则返回 false
     */
    suspend fun isInternetAvailable(): Boolean {
        return withContext(Dispatchers.IO) {
            try {
                val url = URL("https://www.google.com")
                val urlConnection = url.openConnection() as HttpURLConnection
                urlConnection.connectTimeout = 3000 // 3 秒超时
                urlConnection.connect()
                val responseCode = urlConnection.responseCode
                urlConnection.disconnect()
                responseCode == 200
            } catch (e: Exception) {
                false
            }
        }
    }

    /**
     * 检查网络是否实际可用（例如可以访问互联网）
     *
     * @return 如果可以访问互联网，返回 true；否则返回 false
     */
    fun isInternetAvailableNonSuspend(): Boolean {
        return try {
            val url = URL("https://www.google.com")
            val urlConnection = url.openConnection() as HttpURLConnection
            urlConnection.connectTimeout = 3000 // 3 秒超时
            urlConnection.connect()
            val responseCode = urlConnection.responseCode
            urlConnection.disconnect()
            responseCode == 200
        } catch (e: Exception) {
            false
        }
    }

    /**
     * 检查设备是否连接到网络
     *
     * @param context 应用上下文
     * @return 如果已连接到网络，返回 true；否则返回 false
     */
	@Suppress("DEPRECATION")
    private fun isNetworkConnected(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connectivityManager.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnected
    }

    /**
     * 综合判断网络是否正常
     *
     * @param context 应用上下文
     * @return 如果网络连接正常并可以访问互联网，返回 true；否则返回 false
     */
    fun isNetworkAvailable(context: Context): Boolean {
        return isNetworkConnected(context) && isInternetAvailableNonSuspend()
    }
}
